package com.quantumoctopus.magiceatball;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

//test
public class MainActivity extends Activity {

	private String coordinates;
	private Button randomButton;
	private ImageView eballStartImgView;
	private SensorManager mSensorManager;
	private ShakeEventListener mSensorListener;
	public static final String PREFS_EATBALL = "EatBallPrefsFile";
	static SharedPreferences settings;
	SharedPreferences.Editor editor;
	public boolean resultsNotFound;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		randomButton = (Button) findViewById(R.id.randomButton);
		eballStartImgView = (ImageView) findViewById(R.id.eballImgView);
		final Animation rollout = AnimationUtils.loadAnimation(this, R.anim.rollout);

		eballStartImgView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				eballStartImgView.startAnimation(rollout);
				rollout.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationEnd(Animation animation) {
						eballStartImgView.setVisibility(View.INVISIBLE);
						Intent intent = new Intent(MainActivity.this,
								QuizActivity.class);
						intent.putExtra("coordinates", coordinates);
						startActivity(intent);
					}

					@Override
					public void onAnimationRepeat(Animation animation) {

					}

					@Override
					public void onAnimationStart(Animation animation) {
						eballStartImgView.setClickable(false);
					}

				});

			}
		});

		// get shake manager going
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mSensorListener = new ShakeEventListener();
		mSensorListener
				.setOnShakeListener(new ShakeEventListener.OnShakeListener() {

					@Override
					public void onShake() {
						getRandomResult(null);
					}
				});

	
	}
	//animation method
/*	public AnimationSet animateView (final View view){
		AnimationSet set = new AnimationSet(true);
		Animation animation;
		animation = new RotateAnimation(0.0f, 1080.0f,
				view.getWidth() / 2, view
						.getHeight() / 2);
		animation.setDuration(1000);
		animation.setInterpolator(new DecelerateInterpolator());
		set.addAnimation(animation);
		animation = new TranslateAnimation(0, view
				.getWidth(), 0, 0);
		animation.setDuration(1000);
		animation.setInterpolator(new AnticipateInterpolator());
		set.addAnimation(animation);
		set.setAnimationListener(new Animation.AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				eballStartImgView.setClickable(false);
			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				view.setVisibility(View.INVISIBLE);
				Intent intent = new Intent(MainActivity.this,
						QuizActivity.class);
				intent.putExtra("coordinates", coordinates);
				startActivity(intent);
			}
		});
		return set;
		
	}*/

	public void goToLog(View view) {
		Intent intent = new Intent(MainActivity.this, LogActivity.class);
		startActivity(intent);
	}

	public void getRandomResult(View view) {
		Animation spin = AnimationUtils.loadAnimation(this, R.anim.spin);
		eballStartImgView.startAnimation(spin);
		new GetRandomResultTask().execute();
	}

	private class GetRandomResultTask extends AsyncTask<String, Void, Void> {

		@Override
		protected void onPreExecute() {
			// disable shake listener to prevent multiple events
			mSensorManager.unregisterListener(mSensorListener);

			// disable button to prevent multiple clicks
			randomButton.setClickable(false);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			QuizManager qm = new QuizManager();
			// SharedPreferences settings =getPreferences(MODE_PRIVATE);
			settings = getSharedPreferences(PREFS_EATBALL, 0);
			qm.setLl(coordinates);
			qm.LoadPrefs(settings);
			try {

				Result r = qm.getRandomResult();

				Intent intent = new Intent(MainActivity.this,
						ResultActivity.class);
				intent.putExtra("name", r.getName());
				intent.putExtra("display_address", r.getDisplay_address());
				intent.putExtra("phone", r.getPhone());
				intent.putExtra("url", r.getUrl());
				intent.putExtra("id", r.getId());
				intent.putExtra("price", r.getPriceString());
				intent.putExtra("rating", Float.parseFloat(r.getRating()));
				startActivity(intent);
			} catch (Exception e) {
				resultsNotFound = true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// hide spinner
			//progressBar.setVisibility(View.GONE);
			
				if (resultsNotFound) {
					Context context = getApplicationContext();
					CharSequence text = "No Results Found. Try checking your settings";
					int duration = Toast.LENGTH_LONG;

					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					
				}
			
			
			eballStartImgView.clearAnimation();

			// enable button
			randomButton.setClickable(true);
			super.onPostExecute(result);
		}
	}

	// I moved update GPS to on resume, because if a person opens the app for
	// the first time, it will get their location just fine. But if they were to
	// reopen the app from the background, and they're location had changed, we
	// wouldn't know that.
	@Override
	protected void onResume() {
		super.onResume();
		eballStartImgView.setVisibility(View.VISIBLE);
		Animation rollin = AnimationUtils.loadAnimation(this, R.anim.rollin);
		eballStartImgView.startAnimation(rollin);
		eballStartImgView.setClickable(true);
		// enable shake listener
		mSensorManager.registerListener(mSensorListener,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_UI);

		new UpdateGPSAsyncTask().execute(this);
	//	new GetURLTextAsyncTask().execute(this);

	}

	@Override
	protected void onPause() {
		mSensorManager.unregisterListener(mSensorListener);
		super.onPause();
	}

	@Override
	protected void onStop() {
		super.onStop();

		// We need an Editor object to make preference changes.
		// All objects are from android.context.Context

		// SharedPreferences settings =
		// getSharedPreferences(getString(R.string.MAGIC_EAT_BALL_PREFS),
		// MODE_PRIVATE); Unsure if we want more than one settings file
		// SharedPreferences settings = getPreferences(MODE_PRIVATE);
//		settings = getSharedPreferences(PREFS_EATBALL, 0);
//		editor = settings.edit();
//		editor.putString("distance", "5");// Default distance to search for in
//											// range
//		editor.putInt("price", 4);
//		editor.putBoolean("group", true);
//		editor.putBoolean("kids", false);
//		editor.putBoolean("Creditcard", true);
//		editor.putBoolean("handicap", true);
//		editor.putBoolean("alcohol", false);
//		editor.putBoolean("newloc", false);
//		// also just testing
//		editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void goToOptions(View view) {
		Intent intent = new Intent(MainActivity.this, OptionsActivity.class);
		startActivity(intent);
	}

	public class UpdateGPSAsyncTask extends
			AsyncTask<Object, Integer, Exception> {

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected Exception doInBackground(Object... params) {
			double lat;
			double lon; // Emulator testing
			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
			Criteria criteria = new Criteria();

			// Added this one line. Location works now, and is surprisingly
			// accurate for coarse.
			criteria.setAccuracy(Criteria.ACCURACY_COARSE);
			String bestProvider = locationManager.getBestProvider(criteria,
					true);
			Location location = locationManager
					.getLastKnownLocation(bestProvider);
			// locationManager.requestLocationUpdates(bestProvider,0 ,0,
			// loc_listener);

			try {
				lat = location.getLatitude();
				lon = location.getLongitude();
			} catch (NullPointerException e) {
				lat = 34.405920;
				lon = -119.695983;
			}
			StringBuilder sb = new StringBuilder();

			sb.append(Double.toString(lat));
			sb.append(",");
			sb.append(Double.toString(lon));
			coordinates = sb.toString();
	//		coordinates = "34.425958581828425,-119.88632478962093";// for
																	// emulator
																	// testing
			settings = getSharedPreferences(PREFS_EATBALL, 0);
			editor = settings.edit();
			editor.putString("geodata", coordinates);
			editor.commit();
			// R.string.geoloaction=cord; //

			return null;

		}

		@Override
		protected void onPostExecute(Exception error) {

		}
	}

	public class GetURLTextAsyncTask extends
			AsyncTask<Object, Integer, Exception> {

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected Exception doInBackground(Object... params) {
			//int pricedata = ResultsWorker
			//		.getPrice("http://www.yelp.com/biz/los-agaves-santa-barbara"); // test
			return null;

		}

		@Override
		protected void onPostExecute(Exception error) {

		}
	}
	/*
	 * public void Logresult(Result r) Saves result to log in format of
	 * ";;Name::Id" { settings = getSharedPreferences(PREFS_EATBALL, 0); editor
	 * = settings.edit(); StringBuilder sb1 = new StringBuilder();
	 * sb1.append(settings.getString("savedlogslist", "")); if
	 * (settings.getString("savedlogslist", "").isEmpty() != true) {
	 * sb1.append(";;"); } sb1.append(r.getName()); sb1.append("::");
	 * sb1.append(r.getId()); String logstr = sb1.toString();
	 * editor.putString("savedlogslist", logstr); editor.commit(); }
	 */

}
